﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using DotNet.Utilities;

namespace taobaoSpider
{
    /// <summary>
    /// 对设计师页面进行建模。
    /// http://zxn.taobao.com/designer_list.htm?p=3
    /// </summary>
    public class HtmlDesigner
    {
        ShowErrorLogEventHandler ShowMessageHandler = null;

        int _startPageNum = 0;  //采集页面的起始序号。输入参数
        int _endPageNum = 500;

        string _nickName = ""; //设计师的名字  输出参数
        string _designerID = "";  //设计师ID，输出
        string _rzDate = "";  //注册日期  输出
        string _jianjie = "";   //简介    output
        int _templateNum = 0;  //模板的数量。

        string _designerXpath = "";
        System.Data.DataSet _ds = new System.Data.DataSet();  //一个页面有多个设计师信息

        public System.Data.DataSet DS
        {
            get { return _ds; }
        }

        public string DesignerXPath
        {
            set { _designerXpath = value; }
        }

        public string JianJie
        {
            get { return _jianjie; }
        }

        public string RzDate
        {
            get { return _rzDate; }
        }

        public string DesignerID
        {
            get { return _designerID; }
        }

        public int StartPageNum
        {
            set { _startPageNum = value; }
        }
        public int EndPageNum
        {
            set { _endPageNum = value; }
        }

        public string NickName
        {
            get { return _nickName; }
        }

        /// <summary>
        /// 初始化类，其中页码起始从1开始。
        /// </summary>
        /// <param name="startPageNum">从1开始索引的页面</param>
        /// <param name="endPageNum">结束的页面</param>
        /// <param name="designerXpath">设计师信息XPath</param>
        public HtmlDesigner(int startPageNum, int endPageNum, string designerXpath)
        {
            this._startPageNum = startPageNum;
            this._endPageNum = endPageNum;
            this._designerXpath = designerXpath;

            System.Data.DataTable dt = new System.Data.DataTable("template");
            this._ds.Tables.Add(dt);
            this._ds.Tables["template"].Columns.Add("nickname", typeof(string));
            this._ds.Tables["template"].Columns.Add("rzDate", typeof(string));
            this._ds.Tables["template"].Columns.Add("nickname_idnum", typeof(string));
            this._ds.Tables["template"].Columns.Add("jianjie", typeof(string));
            this._ds.Tables["template"].Columns.Add("templateNum", typeof(int));
        }

        /// <summary>
        /// 指定单一页码的多线程调用方式
        /// </summary>
        /// <param name="designerXpath">设计师信息XPath</param>
        public HtmlDesigner(ShowErrorLogEventHandler showMessageHandler, string designerXpath)
        {
            this.ShowMessageHandler = showMessageHandler;
            this._designerXpath = designerXpath;

            System.Data.DataTable dt = new System.Data.DataTable("template");
            this._ds.Tables.Add(dt);
            this._ds.Tables["template"].Columns.Add("nickname", typeof(string));
            this._ds.Tables["template"].Columns.Add("rzDate", typeof(string));
            this._ds.Tables["template"].Columns.Add("nickname_idnum", typeof(string));
            this._ds.Tables["template"].Columns.Add("jianjie", typeof(string));
            this._ds.Tables["template"].Columns.Add("templateNum", typeof(int));
        }

        public void InitDesigner()
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem();
            for (int i = _startPageNum; i <= _endPageNum; i++)
            {
                item.URL = "http://zxn.taobao.com/designer_list.htm?p=" + i.ToString();
                HtmlAgilityPack.HtmlDocument doc = GlobalFun.ParaseToHtml(http.GetHtml(item).Html);
                HtmlAgilityPack.HtmlNodeCollection designerHnc = doc.DocumentNode.SelectNodes(this._designerXpath);
                if (designerHnc != null)
                {
                    foreach (HtmlAgilityPack.HtmlNode node in designerHnc)
                    {
                        try
                        {
                            this._nickName = node.SelectNodes("descendant::dt/descendant::h4")[0].InnerText.Trim();
                            this._jianjie = node.SelectNodes("descendant::dd/descendant::p")[0].InnerText.Trim();
                            //设计师页面url
                            string sjUrl = node.SelectNodes("descendant::dd/descendant::a")[0].Attributes["href"].Value.ToString();
                            this._designerID = sjUrl.Split('=')[1];

                            item.URL = sjUrl;
                            HtmlAgilityPack.HtmlDocument sjDoc = GlobalFun.ParaseToHtml(http.GetHtml(item).Html);
                            this._rzDate = sjDoc.DocumentNode.SelectNodes("//dl[@class='info']/descendant::dd")[0].InnerText.Split('：')[1];
                            HtmlAgilityPack.HtmlNodeCollection templateNumHnc = sjDoc.DocumentNode.SelectNodes("//span[@class='page-skip']");
                            if (templateNumHnc == null)
                            {
                                this._templateNum = 0;
                            }
                            else
                            {
                                //模板页码数量。
                                int templatePageNums = Convert.ToInt32(templateNumHnc[0].InnerText.Split(' ')[0].Trim('共', '页'));
                                if (templatePageNums == 1)
                                {
                                    this._templateNum = sjDoc.DocumentNode.SelectNodes("//div[@id='J_items']/descendant::div").Count;
                                }
                                else
                                {
                                    item.URL = "http://zxn.taobao.com/designer_detail.htm?designerId=" + this._designerID + "&p=" + templatePageNums.ToString();
                                    int lastPageTemplateNums = GlobalFun.ParaseToHtml(http.GetHtml(item).Html).DocumentNode.SelectNodes("//div[@id='J_items']/descendant::div").Count;
                                    this._templateNum = (templatePageNums - 1) * 10 + lastPageTemplateNums;
                                }
                            }
                            System.Data.DataRow dr = this._ds.Tables["template"].NewRow();
                            dr["nickname"] = this._nickName;
                            //dr["nickname"] = this._nickName;
                            dr["rzDate"] = this._rzDate;
                            dr["nickname_idnum"] = this._designerID;
                            dr["jianjie"] = this._jianjie;
                            dr["templateNum"] = this._templateNum;
                            _ds.Tables["template"].Rows.Add(dr);
                        }
                        catch (Exception ex)
                        {
                            GlobalFun.WriteErrorLog("HtmlDesigner:InitDesigner()=>catch", "设计师ID="+this._designerID+"--"+ex.Message);
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 根据页码索引调用。多线程版本的方法。单页面调用
        /// </summary>
        /// <param name="pageIndex">页码</param>
        public void InitDesigner(int pageIndex)
        {
            ShowErrorLogEventArgs e = new ShowErrorLogEventArgs();
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem();
            item.URL = "http://zxn.taobao.com/designer_list.htm?p=" + pageIndex.ToString();
            HtmlAgilityPack.HtmlDocument doc = GlobalFun.ParaseToHtml(http.GetHtml(item).Html);
            HtmlAgilityPack.HtmlNodeCollection designerHnc = doc.DocumentNode.SelectNodes(this._designerXpath);
            if (designerHnc != null)
            {
                foreach (HtmlAgilityPack.HtmlNode node in designerHnc)
                {
                    try
                    {
                        this._nickName = node.SelectNodes("descendant::dt/descendant::h4")[0].InnerText.Trim();
                        this._jianjie = node.SelectNodes("descendant::dd/descendant::p")[0].InnerText.Trim();
                        //设计师页面url
                        string sjUrl = node.SelectNodes("descendant::dd/descendant::a")[0].Attributes["href"].Value.ToString();
                        this._designerID = sjUrl.Split('=')[1];

                        item.URL = sjUrl;
                        HtmlAgilityPack.HtmlDocument sjDoc = GlobalFun.ParaseToHtml(http.GetHtml(item).Html);
                        this._rzDate = sjDoc.DocumentNode.SelectNodes("//dl[@class='info']/descendant::dd")[0].InnerText.Split('：')[1];
                        HtmlAgilityPack.HtmlNodeCollection templateNumHnc = sjDoc.DocumentNode.SelectNodes("//span[@class='page-skip']");
                        if (templateNumHnc == null)
                        {
                            this._templateNum = 0;
                        }
                        else
                        {
                            //模板页码数量。
                            int templatePageNums = Convert.ToInt32(templateNumHnc[0].InnerText.Split(' ')[0].Trim('共', '页'));
                            if (templatePageNums == 1)
                            {
                                this._templateNum = sjDoc.DocumentNode.SelectNodes("//div[@id='J_items']/descendant::div").Count;
                            }
                            else
                            {
                                item.URL = "http://zxn.taobao.com/designer_detail.htm?designerId=" + this._designerID + "&p=" + templatePageNums.ToString();
                                int lastPageTemplateNums = GlobalFun.ParaseToHtml(http.GetHtml(item).Html).DocumentNode.SelectNodes("//div[@id='J_items']/descendant::div").Count;
                                this._templateNum = (templatePageNums - 1) * 10 + lastPageTemplateNums;
                            }
                        }
                        System.Data.DataRow dr = this._ds.Tables["template"].NewRow();
                        dr["nickname"] = this._nickName;
                        //dr["nickname"] = this._nickName;
                        dr["rzDate"] = this._rzDate;
                        dr["nickname_idnum"] = this._designerID;
                        dr["jianjie"] = this._jianjie;
                        dr["templateNum"] = this._templateNum;
                        _ds.Tables["template"].Rows.Add(dr);

                        //System.Windows.Forms.DataGridView dgv=new System.Windows.Forms.DataGridView();
                        //dgv.Name="dgvDesigner";
                        //e.ErrMessage = this._nickName+" "+this._designerID+" "+this._rzDate+" "+this._templateNum;
                        //this.ShowMessageHandler(dgv, e);

                        System.Windows.Forms.Label lblInfo = new System.Windows.Forms.Label();
                        lblInfo.Name = "lblInfo";
                        e.ErrMessage = "第 " + pageIndex.ToString()+" 页"+ this._nickName;
                        e.ErrPosition = "HtmlDesigner:InitDesigner(string pageIndex)";
                        this.ShowMessageHandler(lblInfo, e);
                    }
                    catch (Exception ex)
                    {
                        GlobalFun.WriteErrorLog("HtmlDesigner:InitDesigner()=>catch", "设计师ID=" + this._designerID + "--" + ex.Message);
                    }
                }
            }
        }
    }
}
